import type { TokenType } from '@/api/login/types'
import { CACHE_KEY } from '@/hooks/useCache'
import { decrypt, encrypt } from '@/utils/jsencrypt'
import { useUserStore } from '@/store/modules/user'
import { useFriendStore } from '@/store/modules/friendStore'
import {useChatStore} from '@/store/modules/chatStore.js'
import { currRoute } from '@/utils'

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'

// 获取token
export const getAccessToken = () => {
  // 此处与TokenKey相同，此写法解决初始化时Cookies中不存在TokenKey报错
  const accessToken = uni.getStorageSync(AccessTokenKey)
  return accessToken
}

// 刷新token
export const getRefreshToken = () => {
  return uni.getStorageSync(RefreshTokenKey)
}

// 设置token
export const setToken = (token: TokenType) => {
  uni.setStorageSync(RefreshTokenKey, token.refreshToken)
  uni.setStorageSync(AccessTokenKey, token.accessToken)
}

// 删除token
export const removeToken = () => {
  uni.removeStorageSync(AccessTokenKey)
  uni.removeStorageSync(RefreshTokenKey)
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return `Bearer ${token}`
}

// ========== 租户相关 ==========
export const getTenantId = () => {
  return uni.getStorageSync(CACHE_KEY.TenantId)
  // return uni.getStorageSync(CACHE_KEY.TenantId)
}

export const setTenantId = (username: string|number) => {
  uni.setStorageSync(CACHE_KEY.TenantId, username)

  // wsCache.set(CACHE_KEY.TenantId, username)
}

// ========== 账号相关 ==========

export interface LoginFormType {
  tenantName: string
  mobile: string
  password: string
  rememberMe: boolean
}
export const setLoginForm = (loginForm: LoginFormType) => {
  loginForm.password = encrypt(loginForm.password) as string
  uni.setStorageSync(CACHE_KEY.LoginForm, loginForm)
}

// export const removeLoginForm = () => {
//   wsCache.delete(CACHE_KEY.LoginForm)
// }

export const getLoginForm = () => {
  const loginForm: LoginFormType = uni.getStorageSync(CACHE_KEY.LoginForm)
  if (loginForm) {
    loginForm.password = decrypt(loginForm.password) as string
  }
  return loginForm
}

export async function LogOutFn(toLogin=true) {
  const userStore = useUserStore()
  await userStore.loginOut()
  const friendStore = useFriendStore()
  friendStore.clear()
  const chatStore = useChatStore()
  chatStore.clear()
  if(toLogin){
    const currentPage = currRoute()
    uni.reLaunch({ url: `/pages/login/login?redirect=${currentPage.path}` })
  }
}